
package com.yuhanginfo.modules.sys.service;

import java.util.Date;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.yuhanginfo.common.persistence.Page;
import com.yuhanginfo.common.service.CrudService;
import com.yuhanginfo.modules.sys.entity.Goods;
import com.yuhanginfo.modules.sys.entity.StoreGoods;
import com.yuhanginfo.modules.sys.entity.User;
import com.yuhanginfo.modules.sys.utils.UserUtils;
import com.yuhanginfo.modules.sys.dao.GoodsDao;
import com.yuhanginfo.modules.sys.dao.GoodsMaterielDao;
import com.yuhanginfo.modules.sys.dao.StoreGoodsDao;

/**
 * 门店商品库存管理Service
 * 
 * @author yinhao
 * @version 2017-10-11
 */
@Service
@Transactional(readOnly = true)
public class GoodsStoreStockService extends CrudService<GoodsDao, Goods> {

	@Autowired
	GoodsDao goodsDao;
	
	@Autowired
	GoodsMaterielDao goodsMaterielDao;
	
	@Autowired
	StoreGoodsDao storeGoodsDao;
	


	public Page<Goods> findPage(Page<Goods> page, Goods goods) {
		goods.setPage(page);
		return page.setList(goodsDao.findStoreStockList(goods));
	}

	public Page<Goods> findHistoryStocksPage(Page<Goods> page, Goods goods) {
		goods.setPage(page);
		return page.setList(goodsDao.findHistoryStockList(goods));
	}
	
	@Transactional(readOnly = false,propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void save(Goods goods){
		User user = UserUtils.getUser(); 
		//查询门店_商品关系表
		StoreGoods queryStoreGoods = new StoreGoods();
		queryStoreGoods.setGoodsCode(goods.getCode());
		queryStoreGoods.setStoreCode(goods.getStoreCode());
		StoreGoods resultStoreGoods = storeGoodsDao.getByCode(queryStoreGoods);
		resultStoreGoods.setIsHisttoryStocks(1);
		resultStoreGoods.setSellNum(goods.getStoreGoodsStock());
		//将旧数据变为历史记录
		storeGoodsDao.delete(resultStoreGoods);
		//生成新的数据
		StoreGoods newStoreGoods = new StoreGoods();
		newStoreGoods.setStoreCode(goods.getStoreCode());
		newStoreGoods.setGoodsCode(goods.getCode());
		newStoreGoods.setStock( (resultStoreGoods.getStock() == null ? 0 : resultStoreGoods.getStock()) + goods.getStoreGoodsStock());
		newStoreGoods.setIsHistorySell(0);
		newStoreGoods.setIsHisttoryStocks(0);

		newStoreGoods.setCreateBy(user);
		newStoreGoods.setCreateDate(new Date());
		newStoreGoods.setUpdateBy(user);
		newStoreGoods.setUpdateDate(new Date());
		newStoreGoods.setDelFlag("0");
		storeGoodsDao.insert(newStoreGoods);
	}

}